package com.sat.order.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 死信： 给丢弃的消息
 * 死信的3中情况
 *  1.ttl到期
 *  2.消息高于本身限制的最大长度
 *  3.拒绝签收，并且没有放入原队列中 nack   request = false
 *
 */
@Configuration // 声明这个类是配置类
public class OrderMQConfig {

    //交换机名称
    public static final String TOPIC_EXCHANGE = "add_order_exchange";
    //队列名称
    public static final String QUEUE = "add_order_queue";


    /**
     * 声明交换机
     * @return
     */
    @Bean("topicExchange")
    public Exchange topicExchange(){
        Exchange build = ExchangeBuilder.topicExchange(TOPIC_EXCHANGE).durable(true).build();
        return build;
    }

    /**
     * 声明queue
     * @return
     */
    @Bean("topicQueue")
    public Queue getQueue(){
        // withArgument 设置队列的属性
        Queue queue = QueueBuilder.durable(QUEUE)
                .withArgument("x-message-ttl",60000)
                .withArgument("x-dead-letter-exchange",TOPIC_EXCHANGE_DEAD)
                .withArgument("x-dead-letter-routing-key","sat.order.dead.xx")
                //.withArgument("x-max-length-bytes",500)
                .build();
        return queue;
    }

    @Bean
    public Binding queueExchange(@Qualifier("topicQueue") Queue queue,
                                 @Qualifier("topicExchange") Exchange exchange){
        // with : 绑定规则  #：匹配多个    *：匹配一个
        return BindingBuilder.bind(queue).to(exchange).with("sat.order.*").noargs();
    }



    // 创建死信交换机 （和普通的交换机没有区别） 和死信队列  （和普通的队列没有区别）

    //交换机名称
    public static final String TOPIC_EXCHANGE_DEAD = "add_order_topic_exchange_dead";
    //队列名称
    public static final String QUEUE_DEAD = "add_order_queue_dead";

    @Bean("topicExchangeDead")
    public Exchange topicExchangeDead(){
        Exchange build = ExchangeBuilder.topicExchange(TOPIC_EXCHANGE_DEAD).durable(true).build();
        return build;
    }

    /**
     * 声明queue
     * @return
     */
    @Bean("topicQueueDead")
    public Queue getQueueDead(){
        // withArgument 设置队列的属性
        Queue queue = QueueBuilder.durable(QUEUE_DEAD).build();
        return queue;
    }

    @Bean
    public Binding queueExchangeDead(@Qualifier("topicQueueDead") Queue queue,
                                     @Qualifier("topicExchangeDead") Exchange exchange){
        // with : 绑定规则  #：匹配多个    *：匹配一个
        return BindingBuilder.bind(queue).to(exchange).with("sat.order.dead.#").noargs();
    }

}